package cn.wolfcode.shop.cloud.web.controller;

import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.pay.AlipayConfig;
import cn.wolfcode.shop.cloud.pay.AlipayProperties;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfode.shop.cloud.domain.OrderInfo;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private AlipayProperties alipayProperties;

    @Autowired
    private IOrderInfoService orderInfoService;

    @RequestMapping("/payOrder")
    public void payOrder(String orderNo, HttpServletResponse response) throws IOException, AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayProperties.getGatewayUrl(),alipayProperties.getApp_id(),alipayProperties.getMerchant_private_key(), "json",alipayProperties.getCharset(),alipayProperties.getAlipay_public_key(),alipayProperties.getSign_type());

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturn_url());
        alipayRequest.setNotifyUrl(alipayProperties.getNotify_url());

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderNo;
        //查询出订单对象
        OrderInfo orderInfo = orderInfoService.queryOrderInfo(orderNo);
        //付款金额，必填
        String total_amount = orderInfo.getSeckillPrice()+"";
        //订单名称，必填
        String subject = "1111";
        //商品描述，可空
        String body = "222";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //输出
        out.println(result);
    }

    //同步回调方法，显示数据
    @RequestMapping("/returnUrl")
    public void returnUrl(@RequestParam Map params,HttpServletResponse response) throws AlipayApiException, IOException {
        boolean signVerified = AlipaySignature.rsaCheckV1(params,alipayProperties.alipay_public_key,alipayProperties.getCharset(),alipayProperties.getSign_type()); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            response.sendRedirect("http://localhost:8088/order_detail.html?order="+params.get("out_trade_no"));
        }else {
            response.sendRedirect("http://localhost:8088/50.html");
        }
    }

    //异步回调方法，处理逻辑
    @RequestMapping("/notifyUrl")
    public void notifyUrl(@RequestParam Map params,HttpServletResponse response) throws AlipayApiException, IOException {
        boolean signVerified = AlipaySignature.rsaCheckV1(params,alipayProperties.alipay_public_key,alipayProperties.getCharset(),alipayProperties.getSign_type()); //调用SDK验证签名
        //判断是否验证成功，若验证成功的话，就修改订单状态
        PrintWriter out = response.getWriter();
        if(signVerified) {//验证成功
            String out_trade_no = (String) params.get("out_trade_no");
            orderInfoService.updateStatus(out_trade_no,OrderInfo.STATUS_ACCOUNT_PAID);
            out.println("success");

        }else {//验证失败
            out.println("fail");
        }
    }
}
